package modules.loan.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import luxing.common.service.impl.CommonServiceImpl;
import luxing.util.DateUtil;
import luxing.util.LoginUserUtil;
import modules.loan.entity.LoanContract;
import modules.loan.entity.Loan;
import modules.loan.service.LoanContractService;

/**
 * 
 * @author zzc
 *
 */
@Service("loanContractService")
@Transactional
public class LoanContractServiceImpl extends CommonServiceImpl implements LoanContractService {

	public void save(LoanContract loanContract) {
		// 编号
		String sn = "DK" + DateUtil.dateToStr(new Date(), "yyyyMMdd");
		String hql = "from LoanContract where date(createDate)=? and tenantId=? order by sn desc";
		List<LoanContract> loanContractList = listByHql(hql, new Date(), LoginUserUtil.getLoginUser().getTenantId());
		if (CollectionUtils.isNotEmpty(loanContractList)) {
			String endNum = loanContractList.get(0).getSn().substring(10);
			endNum = String.valueOf(Integer.valueOf(endNum).intValue() + 1);
			if (endNum.length() == 1) {
				endNum = "00" + endNum;
			} else if (endNum.length() == 2) {
				endNum = "0" + endNum;
			}
			sn = sn + endNum;
		} else {
			sn = sn + "001";
		}
		loanContract.setSn(sn);
		// 利息
		BigDecimal interest = new BigDecimal(0);
		// 总计金额
		BigDecimal totalAmount = new BigDecimal(0);
		for (Loan loan : loanContract.getLoanList()) {
			interest = interest.add(loan.getInterest());
			totalAmount = totalAmount.add(loan.getPrincipal().add(loan.getInterest()));
		}
		loanContract.setInterest(interest);
		loanContract.setTotalAmount(totalAmount);
		loanContract.setRealPrincipal(new BigDecimal(0));
		loanContract.setRealInterest(new BigDecimal(0));
		loanContract.setRealTotalAmount(new BigDecimal(0));
		loanContract.setOweAmount(totalAmount);
		super.save(loanContract);
		/** 还款计划 **/
		for (Loan loan : loanContract.getLoanList()) {
			loan.setSn(sn + "-" + loan.getPeriod());
			loan.setLoanContract(loanContract);
			loan.setTotalAmount(loan.getPrincipal().add(loan.getInterest()));
			loan.setRealPrincipal(new BigDecimal(0));
			loan.setRealInterest(new BigDecimal(0));
			loan.setRealTotalAmount(new BigDecimal(0));
			loan.setOweAmount(loan.getTotalAmount());
			super.save(loan);
		}
	}

	public List<LoanContract> listByOwner(String ownerId) {
		String hql = "from LoanContract where owner.id=? and tenantId=?";
		return listByHql(hql, ownerId, LoginUserUtil.getLoginUser().getTenantId());
	}

	public List<LoanContract> listNonByOwner(String ownerId) {
		String hql = "from LoanContract where owner.id=? and (status=? or status=?) and tenantId=?";
		return listByHql(hql, ownerId, LoanContract.STATUS_ING, LoanContract.STATUS_NO,
				LoginUserUtil.getLoginUser().getTenantId());
	}

}
